package fileUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JTextArea;
import javax.swing.SwingWorker;

public class SendFile {

	public SendFile() {

	}

	/**
	 * 发送文件
	 * @param requestURL： post API的地址
	 * @param fileDir：发送文件的目录，会递归发送全部文件
	 * @param fieldName：这个可以忽略
	 * @return
	 */
	public static String Send(String requestURL, String fileDir, String fieldName) {
		String charset = "UTF-8";
		String resultStr = "";
		List<File> fileList = getFileLists(fileDir);

		try {
			MultipartUtility multipart = new MultipartUtility(requestURL, charset);

			multipart.addHeaderField("User-Agent", "User-Agent");
			multipart.addFormField("keyword", "keywords");

			for (File fi : fileList) {
				multipart.addFilePart(fieldName, fi);
			}

			List<String> response = multipart.finish();

			System.out.println("SERVER REPLIED:");

			for (String line : response) {
				System.out.println(line);
				resultStr += line + "\n\r";
			}
			return resultStr;
		} catch (IOException ex) {
			System.err.println(ex);
			return ex.getMessage();
		}
	}

	public static List<File> getFileLists(String strPath) {
		List<File> fileList = new ArrayList<File>();
		File dir = new File(strPath);
		File[] files = dir.listFiles();
		if (files == null)
			return null;
		for (int i = 0; i < files.length; i++) {
			if (files[i].isDirectory()) {
				getFileLists(files[i].getAbsolutePath());
			} else {
				// fileList.add(files[i].getAbsolutePath());
				fileList.add(files[i]);
			}
		}

		return fileList;
	}

	private static void changeText(JTextArea jTextArea, String str) {

		jTextArea.setText(str);
	}

	public static void swingworkCallback(final JTextArea jTextArea, final String fileAPIurl, final String fileFolder) {
		final SwingWorker worker = new SwingWorker() {

			@Override
			protected Object doInBackground() throws Exception {
				try {
					String backStr = SendFile.Send(fileAPIurl, fileFolder, "fieldname");
					changeText(jTextArea, backStr);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
				return null;
			}

		};
		worker.execute();
	}

}
